package com.cjdes.recipes4u;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class SubmitEmail extends Activity {

	private String FROM_ADDRESS = "recipe@homemade.com";
	private String TO_ADDRESS = "jamie@cj-des.com";
	private String SMTP_HOST_NAME = "mail.cj-des.com";
	private String VALIDATE_ERROR_MESSAGE = null;
	private boolean THREAD_ERROR = false;
	Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_submit_email);
		context = getBaseContext();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_submit_email, menu);
		return true;
	}

	public void submitRecipe(View view) {

		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {

				Properties props = new Properties();
				props.put("mail.smtp.host", SMTP_HOST_NAME);
				Session session = Session.getInstance(props);
				try {
					MimeMessage message = new MimeMessage(session);

					// Set From: header field of the header.
					message.setFrom(new InternetAddress(FROM_ADDRESS,
							"Recipe Submission"));

					// Set To: header field of the header.
					message.addRecipient(Message.RecipientType.TO,
							new InternetAddress(TO_ADDRESS));

					// Set Subject: header field
					message.setSubject("Recipe submission");

					// Now set the actual message
					message.setText(convertRecipe());

					// Send message
					Transport.send(message);
					System.out.println("Sent message successfully....");
				} catch (Exception e) {
					THREAD_ERROR = true;
				}

			}

		});
		if (getConnectivityStatus(this) > 0) {
			System.out.println("Network available");
			if (validateBoxes()) {
				thread.setDaemon(true);
				thread.start();

				if (THREAD_ERROR == true) {
					AlertDialog.Builder emailError = new AlertDialog.Builder(
							this);
					emailError.setMessage("Error sending recipe");
					emailError.setTitle("Error Submitting Recipe");
					emailError.setPositiveButton("OK", null);
					emailError.setCancelable(true);
					emailError.create().show();
				} else {
					this.finish();
				}
			} else {
				AlertDialog.Builder emailError = new AlertDialog.Builder(this);
				emailError
						.setMessage(VALIDATE_ERROR_MESSAGE);
				emailError.setTitle("Validation Error");
				emailError.setPositiveButton("OK", null);
				emailError.setCancelable(true);
				emailError.create().show();
			}

		} else {
			AlertDialog.Builder emailError = new AlertDialog.Builder(this);
			emailError
					.setMessage("You need to have a data connection to submit a recipe");
			emailError.setTitle("Error Submitting Recipe");
			emailError.setPositiveButton("OK", null);
			emailError.setCancelable(true);
			emailError.create().show();
		}

	}

	private boolean validateBoxes() {
		EditText recipeName = (EditText) findViewById(R.id.recipeTitle);
		EditText recipeIngredients = (EditText) findViewById(R.id.ingredients);
		EditText recipeMethod = (EditText) findViewById(R.id.method);
		EditText recipeSubmitFirstName = (EditText) findViewById(R.id.firstname);
		EditText recipeSubmitLastName = (EditText) findViewById(R.id.lastname);
		EditText recipeSubmitEmailAddress = (EditText) findViewById(R.id.email);
		
		if (recipeName.getText().length() == 0){
			VALIDATE_ERROR_MESSAGE = "You must give your recipe a name";
			return false;
		}
		if (recipeIngredients.getText().length() == 0){
			VALIDATE_ERROR_MESSAGE = "Your recipe must have ingredients";
			return false;
		}
		if (recipeMethod.getText().length() == 0){
			VALIDATE_ERROR_MESSAGE = "Your recipe must have a method";
			return false;
		}
		if (recipeSubmitFirstName.getText().length() == 0){
			VALIDATE_ERROR_MESSAGE = "You must supply your first name";
			return false;
		}
		if (recipeSubmitLastName.getText().length() == 0){
			VALIDATE_ERROR_MESSAGE = "You must supply your last name";
			return false;
		}
		if (recipeSubmitEmailAddress.getText().length() == 0){
			VALIDATE_ERROR_MESSAGE = "You must supply your email address";
			return false;
		}
		return true;
	}

	private String convertRecipe() {
		EditText recipeName = (EditText) findViewById(R.id.recipeTitle);
		EditText recipeIngredients = (EditText) findViewById(R.id.ingredients);
		EditText recipeMethod = (EditText) findViewById(R.id.method);
		EditText recipeSubmitFirstName = (EditText) findViewById(R.id.firstname);
		EditText recipeSubmitLastName = (EditText) findViewById(R.id.lastname);
		EditText recipeSubmitEmailAddress = (EditText) findViewById(R.id.email);
		String androidId = Secure.getString(getContentResolver(),
				Secure.ANDROID_ID);
		StringBuilder builder = new StringBuilder();
		builder.append("Recipe submitted by: \n");
		builder.append(recipeSubmitFirstName.getText().toString() + " "
				+ recipeSubmitLastName.getText().toString() + "\n");
		builder.append("Sent from: "
				+ recipeSubmitEmailAddress.getText().toString() + "\n");
		builder.append("Recipe Name: " + recipeName.getText().toString() + "\n");
		builder.append("Ingredients: " + recipeIngredients.getText().toString()
				+ "\n");
		builder.append("Method: " + recipeMethod.getText().toString() + "\n");
		builder.append("Sent from device: " + androidId);
		return builder.toString();

	}

	public static int TYPE_WIFI = 1;
	public static int TYPE_MOBILE = 2;
	public static int TYPE_NOT_CONNECTED = 0;

	public static int getConnectivityStatus(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		if (null != activeNetwork) {
			if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
				return TYPE_WIFI;

			if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
				return TYPE_MOBILE;
		}
		return TYPE_NOT_CONNECTED;
	}
}
